<script setup>
import { ref } from 'vue'
import { request } from '@/utils/request'

const file = ref(null)
let fileData = null
let data = ref([])
// 选择图片
const changeFile = (e) => {
  fileData = e.target.files[0]
  console.log(fileData)
  let chunkList = []
  if (fileData) {
    // 进行文件切片，并且给每一个分片文件添加文件名(整体)、分片文件、分片文件名
    chunkList = createChunk(fileData)
    console.log(chunkList)
    data.value = chunkList.map(({ file }, index) => ({
      file,
      chunkName: fileData.name + '-' + index,
      fileName: fileData.name
    }))
    // 合并上传
    requestLoad(data.value)
  }
}
// 点击按钮上传图片
const uploadFile = () => {
  if (file.value) {
    file.value.click()
  }
}
// 创建切片文件
// 核心：使用slice方法将文件进行指定大小的分隔
const createChunk = (file, size = 1024 * 1024) => {
  // 包含分片文件的数组
  const chunkList = []
  // 创建每次切片的文件头
  let cur = 0
  while (cur <= file.size) {
    chunkList.push({ file: file.slice(cur, cur + size) })
    cur += size
  }
  return chunkList
}
// 给每一个切片文件添加请求函数，进行合并上传，只有全部上传成功，才表示本次分片上传成功
const requestLoad = async (list) => {
  const requestList = list
    .map(({ file, chunkName, fileName }) => {
      const fd = new FormData()
      fd.append('file', file)
      fd.append('chunkName', chunkName)
      fd.append('fileName', fileName)
      return { fd }
    })
    .map(({ fd }) => request('http://localhost:3000', fd))
  await Promise.all(requestList)
}
</script>

<template>
  <div class="upload-page">
    <input type="file" hidden @change="changeFile" ref="file" />
    <button @click="uploadFile">点击上传</button>
  </div>
</template>

<style lang="scss" scoped></style>
